import Vue from 'vue'
import VueRouter from 'vue-router'
import {
  storage
} from '@/assets/js/storage'
import routes from './routes'
import {
  callhandler
} from '@/assets/js/bridge'
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'hash', // 'history'
  routes: routes,
  // 页面初次访问定位到开始
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }

  }
})

// 添加路由拦截器
router.beforeEach((to, from, next) => {
  try {
    document.title = to.matched[0].meta.title
  } catch (e) {}

  // 必须有next()才可以显示
  // next()

  // 获取token
  let token = storage.get('token')
  // 判断进入首页必须先获取用户token，防止用户重复登陆出现token错误
  if (to.name === 'test' || to.name === 'payList') {
    try {
      // 调用原生获取用户信息并储存到本地
      callhandler("getUserInfo", {}, res => {
        let resData = JSON.parse(res)
        storage.set('token', resData.token)
        storage.set('mobile', resData.mobile)
        next()
      })
    } catch (e) {
      next()
    }
    next()
  }

  // 判断requireAuth字段，是否需要验证
  if (to.meta.requireAuth) {
    // 若没有token就请i去原生获取token
    if (token === false) {
      try {
        callhandler("getUserInfo", {}, res => {
          let resData = JSON.parse(res)
          storage.set('token', resData.token)
          storage.set('mobile', resData.mobile)
          next()
        })
      } catch (e) {
        next()
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router